package com.niiwoo.civet.trade.service.dubbo.invest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.niiwoo.civet.account.service.AccountDubboService;
import com.niiwoo.civet.trade.service.invest.InvestJobDubboService;
import com.niiwoo.civet.trade.service.local.invest.AutoBatchInvestService;
import com.niiwoo.civet.trade.service.local.invest.InvestQueueService;

/**
 * Created by zhangwanli on 2017/11/22.
 */
@Service(version = "1.0.0")
public class InvestJobDubboServiceImpl implements InvestJobDubboService {

    private static final Logger logger = LoggerFactory.getLogger(InvestJobDubboServiceImpl.class);

    @Autowired
    private AutoBatchInvestService autoBatchInvestService;
    @Autowired
    private InvestQueueService investQueueService;
    @Reference(version = "1.0.0")
    private AccountDubboService accountDubboService;

    @Override
    public void revertAutoInvestorQueue() {
    	long time = System.currentTimeMillis();
        logger.info("执行自动投资人回到队列任务---->start");
        investQueueService.logQueue();
        // 十分钟前
     	Long tenMinuterAgo = System.currentTimeMillis() - 10 * 60 * 1000;
     	//投资人回队列
        autoBatchInvestService.revertAutoInvest(tenMinuterAgo);
        //可以投资的标回队列
        autoBatchInvestService.revertProject(tenMinuterAgo);
        logger.info("执行自动投资人回到队列任务---->end");
        investQueueService.logQueue();
        logger.info("休息区回归定时任务完成，总耗时{}",System.currentTimeMillis()-time);
    }

//    public void revertAutoInvestorQueueFromStash() {
//        Set<ZSetOperations.TypedTuple<String>> tupleSet = redisTemplate.opsForZSet().rangeWithScores(TradeRedisKey.AUTO_INVESTORS_STASH, 0, -1);
//        if (tupleSet != null && !tupleSet.isEmpty()) {
//            Map<String, Set<ZSetOperations.TypedTuple<String>>> groupBySourceQueue = new HashMap<>();
//            for (ZSetOperations.TypedTuple<String> tuple : tupleSet) {
//                String value = tuple.getValue();
//                InvestQueueService.AutoInvestorValueDTO dto = JSON.parseObject(value, InvestQueueService.AutoInvestorValueDTO.class);
//                String investorId = dto.getInvestorId();
//                String sourceQueue = dto.getSourceQueue();
//                //过滤调已存在于自动投资人队列的人，不存在才还原回去
//                ZSetOperations.TypedTuple<String> newTuple = new DefaultTypedTuple<>(investorId, tuple.getScore());
//                Set<ZSetOperations.TypedTuple<String>> set = groupBySourceQueue.computeIfAbsent(sourceQueue, k -> new HashSet<>());
//                set.add(newTuple);
//            }
//            groupBySourceQueue.forEach((k, v) -> redisTemplate.opsForZSet().add(k, v));
//            redisTemplate.opsForZSet().removeRange(TradeRedisKey.AUTO_INVESTORS_STASH, 0, -1);
//        }
//    }

//    private void revertAutoInvestorQueueFromLounge() {
//        List<SysInvestConfig> sysInvestConfigList = autoBatchInvestService.querySysInvestConfigList();
//        BoundZSetOperations<String, String> zSetOps = redisTemplate.boundZSetOps(TradeRedisKey.AUTO_INVESTORS_LOUNGE);
//        long _10_min_ago = new DateTime().minusMinutes(10).toDate().getTime();
//        Set<String> values = zSetOps.rangeByScore(Double.MIN_VALUE, _10_min_ago);
//        int removeCount = 0;
//        int revertCount = 0;
//        for (String value : values) {
//            InvestQueueService.AutoInvestorValueDTO dto = JSON.parseObject(value, InvestQueueService.AutoInvestorValueDTO.class);
//            String sourceQueue = dto.getSourceQueue();
//            String investorId = dto.getInvestorId();
//            if (existsInInvestorQueue(sourceQueue, investorId) || !stillShouldEnqueue(sourceQueue, investorId, sysInvestConfigList)) {
//                zSetOps.remove(value);
//                removeCount++;
//            } else {
//                if (hasInvestBalance(investorId)) {
//                    double priority = Calculator.investPriority(dto.getWeight());
//                    redisTemplate.opsForZSet().add(sourceQueue, investorId, priority);
//                    revertCount++;
//                    zSetOps.remove(value);
//                    removeCount++;
//                }
//            }
//        }
//        logger.info("捡回10分钟之前进入自动投资人休息区的投资人,休息区共{}人,休息区移除{}人,回到队列{}人", values.size(), removeCount, revertCount);
//    }

//    private void revertAutoInvestProjectFromStash() {
//        BoundZSetOperations<String, String> zSetOps = redisTemplate.boundZSetOps(TradeRedisKey.AUTO_INVEST_PROJECT_STASH);
//        long _3_min_ago = new DateTime().minusMinutes(3).toDate().getTime();
//        Set<String> values = zSetOps.rangeByScore(Double.MIN_VALUE, _3_min_ago);
//        for (String value : values) {
//            rabbitTemplate.convertAndSend(RabbitConstant.Exchange.AUTO_INVEST_PROJECT, RabbitConstant.RoutingKey.AUTO_INVEST_PROJECT, value);
//            redisTemplate.opsForZSet().remove(TradeRedisKey.AUTO_INVEST_PROJECT_STASH, value);
//            logger.info("从自动投资标的暂存区恢复标的到MQ,projectId={}", value);
//        }
//        logger.info("捡回3分钟之前进入标的暂存区的标的,暂存区共{}个", values.size());
//    }





}
